package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.mapper.UserMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    AddressBookMapper addressBookMapper;

    @Autowired
    ShoppingCartMapper shoppingCartMapper;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    WeChatPayUtil weChatPayUtil;

    @Autowired
    WebSocketServer webSocketServer;

    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        // 1.处理异常情况
        Long userId = BaseContext.getCurrentId();
        AddressBook address = addressBookMapper.getDefaultAddress(userId);

        if(address == null) {
            // 地址簿找不到
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        // 购物车数据
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.getListByUserId(userId);

        if(shoppingCarts == null || shoppingCarts.isEmpty()) {
            // 购物车数据不能为空
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // 2.插入订单表
        Orders orders = Orders.builder()
                .orderTime(LocalDateTime.now())
                .status(Orders.PENDING_PAYMENT)
                .payStatus(Orders.UN_PAID)
                .number(String.valueOf(System.currentTimeMillis()))
                .phone(address.getPhone())
                .consignee(address.getConsignee())
                .address(address.getCityName() + address.getDistrictName() + address.getDetail())
                .userId(BaseContext.getCurrentId())
                .build();


        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orderMapper.insert(orders);

        // 3.插入订单详情表
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart cart: shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }
        orderMapper.insertBatch(orderDetails);

        // 4.删除购物车
        shoppingCartMapper.deleteAllByUserId(userId);

        // 5.封装返回类
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
    }

    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getByUserId(userId);

        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal("0.01"), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
        JSONObject jsonObject = new JSONObject();
        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        paySuccess(ordersPaymentDTO.getOrderNumber());
        return vo;
    }

    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        // 消息提醒
        Map<String, Object> map = new HashMap<>();
        map.put("type", 1);
        map.put("orderId", ordersDB.getUserId());
        map.put("content", "订单号" + outTradeNo);

        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
    }

    @Override
    public OrderVO getOrderDetail(Long id) {
        OrderVO orderVO = new OrderVO();
        // 查询order
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        BeanUtils.copyProperties(orders, orderVO);

        // 查询order_detail
        List<OrderDetail> orderDetails = orderMapper.getByOrderIdForDetail(id);
        orderVO.setOrderDetailList(orderDetails);

        return orderVO;
    }

    @Override
    public PageResult getOrderList(Long userId, Integer status) {
        Page<Orders> page = orderMapper.getByUserIdForOrders(userId, status);
        if (page == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        // 包装结果
        List<Orders> ordersList = page.getResult();
        List<OrderVO> result = new ArrayList<>();
        for (Orders order: ordersList) {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);
            List<OrderDetail> details = orderMapper.getByOrderIdForDetail(order.getId());
            orderVO.setOrderDetailList(details);
            result.add(orderVO);
        }

        return new PageResult(page.getTotal(), result);
    }

    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("type", 2);
        map.put("orderId", id);
        map.put("content", "订单号" + orders.getNumber());
        String jsonString = JSON.toJSONString(map);

        webSocketServer.sendToAllClient(jsonString);
    }

    @Override
    public void cancel(Long id, String reason) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(reason);
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    @Override
    public PageResult queryPage(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 查询符合的orders
        Page<Orders> page = orderMapper.getAllOrders(ordersPageQueryDTO);

        // 判断异常
        if (page == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        // 包装相应的detail
        List<Orders> ordersList = page.getResult();
        List<OrderVO> result = new ArrayList<>();
        for (Orders orders: ordersList) {
            OrderVO orderVO = new OrderVO();

            // 复制order信息
            BeanUtils.copyProperties(orders, orderVO);

            // 获取相应菜品或套餐列表
            List<String> dishesList = orderMapper.getDishesString(orders.getId());
            orderVO.setOrderDishes(dishesList.toString());

            result.add(orderVO);
        }

        return new PageResult(page.getTotal(), result);
    }

    @Override
    public OrderStatisticsVO getStatistics() {
        return orderMapper.getStatistics();
    }

    @Override
    public void confirm(Long id) {
        Orders orders = new Orders();
        orders.setStatus(Orders.CONFIRMED);
        orders.setId(id);
        orderMapper.update(orders);
    }

    @Override
    public void reject(Long id, String rejectionReason) {
        Orders orders = new Orders();
        orders.setStatus(Orders.CANCELLED);
        orders.setId(id);
        orders.setCancelTime(LocalDateTime.now());
        orders.setRejectionReason(rejectionReason);
        orders.setCancelReason("商家拒单");
        orderMapper.update(orders);
    }

    @Override
    public void delivery(Long id) {
        Orders orders = new Orders();
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orders.setId(id);
        orders.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    @Override
    public void complete(Long id) {
        Orders orders = new Orders();
        orders.setStatus(Orders.COMPLETED);
        orders.setId(id);
        orderMapper.update(orders);
    }


}
